use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Post {
    pub title: String,
    pub slug: String,
    pub content: String,
    pub published: bool,
}

#[derive(Debug)]
pub struct BlogState {
    pub posts: Vec<Post>,
}

impl BlogState {
    pub fn new() -> Self {
        Self { posts: vec![] }
    }

    pub fn add_post(&mut self, post: Post) {
        self.posts.push(post);
    }

    pub fn add_post_of(&mut self, title: String, content: String, published: bool) {
        let slug = title.to_lowercase().replace(" ", "-");
        self.posts.push(Post {
            title,
            slug,
            content,
            published,
        });
    }

    pub fn get_published(&self) -> Vec<&Post> {
        self.posts.iter().filter(|p| p.published).collect()
    }

    pub fn find_by_slug(&self, slug: &str) -> Option<&Post> {
        self.posts.iter().find(|p| p.slug == slug)
    }
}
